package com.leon.androidcoursedesign.servers;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.leon.androidcoursedesign.R;
import com.leon.androidcoursedesign.ui.activitys.toolBoxActivity.MusicActivity;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class MusicService extends Service {
    private MediaPlayer mediaPlayer;
    private Timer timer;

    //播放停止时的数值与长度之间的差值
    private final int differenceRange = 100;

    @Override
    public void onCreate() {
        super.onCreate();

        mediaPlayer = new MediaPlayer();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        return new MusicControl();
    }

    /*
     * 任意一次unbindService()方法，都会触发这个方法
     * 用于释放一些绑定时使用的资源
     * @param intent
     * @return
     */
    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    private void addTimer() {

        if (timer == null) {
            //计时器对象
            timer = new Timer();

            //计时任务
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    //该线程用来获取当前播放进度
                    if (mediaPlayer.isPlaying()) {
                        int currentPosition = mediaPlayer.getCurrentPosition();

                        //获取总长度
                        int duration = mediaPlayer.getDuration();

                        //利用message给主线程发消息更新seekBar进度
                        Message message = MusicActivity.handler.obtainMessage();

                        Bundle bundle = new Bundle();
                        bundle.putInt("duration", duration);
                        bundle.putInt("currentPosition", currentPosition);

                        //设置发送的消息内容
                        message.setData(bundle);

                        //发送消息给主线程
                        MusicActivity.handler.sendMessage(message);
                    }
                }
            };

            //开启计时任务，第一次开启五毫秒后执行，以后是每500毫秒执行一次
            timer.schedule(timerTask, 5, 500);
        }
    }

    public class MusicControl extends Binder {
        public void play(Uri uri) {
            mediaPlayer.reset();

            playMusic(uri);

            addTimer();
        }

        public void pause() {
            mediaPlayer.pause();
        }

        public void continuePlay() {
            mediaPlayer.start();
        }

        public void seekPlayProgress(int progress) {
            mediaPlayer.seekTo(progress);
        }
    }

    //播放音乐
    private void playMusic(Uri uri) {
        try {
            if (mediaPlayer == null) {
                mediaPlayer = new MediaPlayer();
            }

            if (mediaPlayer.isPlaying()) {
                onDestroy();

                mediaPlayer = new MediaPlayer();
            }

            mediaPlayer.setDataSource(getApplicationContext(), uri);

            //准备数据监听
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                }
            });

            //播放完毕监听
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    int duration = mp.getDuration();
                    int currentPosition = mp.getCurrentPosition();

                    if (duration != 0 && currentPosition != 0) {
                        //确定范围
                        if (mp.getDuration() - mp.getCurrentPosition() <= differenceRange) {
                            MusicActivity.music_imageView_control.setImageResource(R.drawable.music_icon_pause);
                            MusicActivity.rotation.pause();
                            MusicActivity.musicState = 2;
                        }
                    }
                }
            });

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {

                    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                        mediaPlayer.seekTo(0);
                        Toast.makeText(MusicService.this, "重新播放中", Toast.LENGTH_SHORT).show();
                    }
                    return false;
                }
            });

            mediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.release();
        mediaPlayer = null;

        //取消计时任务
        if (timer != null) {
            timer.cancel();
        }

        super.onDestroy();
    }
}
